package com.kira.scaffoldmvc.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 配置第一个数据源（ds1）的相关组件
 * 负责管理ds1数据源的连接、事务和MyBatis会话
 */
@Configuration
// 仅扫描ds1包下的Mapper，并关联ds1的SqlSessionTemplate
@MapperScan(
        basePackages = "com.kira.scaffoldmvc.Mapper.ds1",
        sqlSessionTemplateRef = "ds1SqlSessionTemplate"
)
public class Ds1DataSourceConfig {

    // 读取ds1数据源的配置参数
    @Value("${spring.datasource.ds1.url}")
    private String url;
    @Value("${spring.datasource.ds1.username}")
    private String userName;
    @Value("${spring.datasource.ds1.password}")
    private String passWord;
    @Value("${spring.datasource.ds1.driver-class-name}")
    private String driver;

    /**
     * 创建ds1数据源实例
     */
    @Primary // 标记为主数据源，解决默认注入冲突
    @Bean(name = "ds1DataSource")
    public DataSource ds1DataSource() {
        DataSourceProperties properties = new DataSourceProperties();
        properties.setUsername(userName);
        properties.setUrl(url);
        properties.setPassword(passWord);
        properties.setDriverClassName(driver);
        return properties.initializeDataSourceBuilder().build();
    }

    /**
     * 创建ds1数据源的事务管理器
     */
    @Primary
    @Bean(name = "ds1TransactionManager")
    public DataSourceTransactionManager ds1TransactionManager() {
        return new DataSourceTransactionManager(ds1DataSource());
    }

    /**
     * 创建ds1数据源的SqlSessionFactory（关联ds1数据源和映射文件）
     */
    @Primary
    @Bean(name = "ds1SqlSessionFactory")
    public SqlSessionFactory ds1SqlSessionFactory(@Qualifier("ds1DataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        // 指定ds1的Mapper XML文件路径
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:com/kira/scaffoldmvc/Mapper/ds1/*.xml"));
        // 启用驼峰命名转换
        sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return sessionFactory.getObject();
    }

    /**
     * 创建ds1数据源的SqlSessionTemplate（关联ds1的SqlSessionFactory）
     */
    @Primary
    @Bean(name = "ds1SqlSessionTemplate")
    // 方法名与Bean名保持一致，避免混淆
    public SqlSessionTemplate ds1SqlSessionTemplate(@Qualifier("ds1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}